<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --thu-purple: #82318E;
            --thu-purple-light: #9b4da7;
            --thu-purple-dark: #6a2875;
        }
        
        body {
            background-color: #ffffff;
            color: #1a1a1a;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        .main-container {
            display: flex;
            height: 100vh;
        }

        .sidebar {
            width: 260px;
            background-color: #f9f9f9;
            border-right: 1px solid #e6e6e6;
            padding: 20px;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }

        .new-chat-btn {
            background-color: var(--thu-purple);
            color: white;
            border: none;
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 20px;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
            gap: 8px;
            width: 100%;
            font-size: 14px;
        }

        .new-chat-btn svg {
            width: 16px;
            height: 16px;
            fill: currentColor;
        }

        .new-chat-btn:hover {
            background-color: var(--thu-purple-light);
        }

        .chat-history {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .chat-history-item {
            padding: 12px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 14px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
            position: relative;
        }

        .chat-history-item:hover {
            background-color: #f0f0f0;
        }

        .chat-history-item.active {
            background-color: #f0f0f0;
            font-weight: 500;
        }

        .chat-history-item svg {
            width: 16px;
            height: 16px;
            fill: var(--thu-purple);
            opacity: 0.7;
        }

        .chat-history-item .delete-btn {
            position: absolute;
            right: 8px;
            opacity: 0;
            transition: opacity 0.2s ease;
            background: none;
            border: none;
            color: #ff4444;
            padding: 4px;
            border-radius: 4px;
        }

        .chat-history-item:hover .delete-btn {
            opacity: 1;
        }

        .chat-history-item .delete-btn:hover {
            background-color: rgba(255, 68, 68, 0.1);
        }

        .chat-history-title {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .chat-container {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            max-width: none;
            margin: 0;
            padding: 0;
            background-color: #ffffff;
        }

        .chat-header {
            padding: 16px 24px;
            border-bottom: 1px solid #e6e6e6;
            background-color: #ffffff;
        }

        .chat-messages {
            flex-grow: 1;
            overflow-y: auto;
            padding: 24px;
            background-color: #ffffff;
        }

        .message {
            max-width: 800px;
            margin: 0 auto 24px;
            padding: 16px 24px;
            border-radius: 8px;
            line-height: 1.6;
            position: relative;
            animation: messageAppear 0.3s ease-out forwards;
        }

        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .user-message {
            background-color: #f5f5f5;
            opacity: 1;
        }

        .assistant-message {
            background-color: #ffffff;
            border: 1px solid #e6e6e6;
            opacity: 1;
        }

        .message-content {
            white-space: pre-wrap;
            word-break: break-word;
            opacity: 1;
        }

        .message-time {
            font-size: 12px;
            color: #999;
            margin-top: 8px;
        }

        .message-source {
            position: absolute;
            top: 8px;
            right: 8px;
            font-size: 12px;
            color: #999;
            background-color: #f5f5f5;
            padding: 2px 6px;
            border-radius: 4px;
        }

        .typing-indicator {
            display: inline-block;
            margin-left: 4px;
        }

        .typing-indicator span {
            display: inline-block;
            width: 4px;
            height: 4px;
            background-color: #999;
            border-radius: 50%;
            margin: 0 2px;
            animation: typing 1s infinite;
        }

        .typing-indicator span:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator span:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes typing {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-4px); }
        }

        .input-container {
            border-top: 1px solid #e6e6e6;
            padding: 24px;
            background-color: #ffffff;
        }

        .input-group {
            max-width: 800px;
            margin: 0 auto;
            position: relative;
            display: flex;
            align-items: flex-end;
        }

        #message-input {
            border: 1px solid #e6e6e6;
            border-radius: 6px;
            padding: 12px;
            padding-right: 50px;
            font-size: 16px;
            resize: none;
            min-height: 48px;
            max-height: 200px;
            flex-grow: 1;
            transition: border-color 0.2s ease;
        }

        #message-input:focus {
            outline: none;
            border-color: var(--thu-purple);
            box-shadow: 0 0 0 2px rgba(130, 49, 142, 0.1);
        }

        .send-button-container {
            position: absolute;
            right: 8px;
            bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .send-button {
            width: 32px;
            height: 32px;
            padding: 6px;
            display: flex !important;
            align-items: center;
            justify-content: center;
            border: none;
            border-radius: 6px;
            background: transparent;
            transition: all 0.2s ease;
            position: relative;
        }

        .send-button svg {
            width: 20px;
            height: 20px;
            fill: var(--thu-purple);
        }

        /* 禁用状态 */
        .send-button:disabled {
            opacity: 0.3;
            cursor: not-allowed;
            background: transparent;
        }

        .send-button:disabled svg {
            fill: var(--thu-purple);
        }

        /* 可点击状态 */
        .send-button:not(:disabled) {
            opacity: 1;
            cursor: pointer;
            background-color: var(--thu-purple);
        }

        .send-button:not(:disabled) svg {
            fill: white;
        }

        /* 加载状态 */
        .send-button.loading {
            opacity: 0.7;
            cursor: wait;
            background-color: var(--thu-purple);
        }

        .loading-spinner {
            position: absolute;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            display: none;
        }

        .send-button.loading .loading-spinner {
            display: block;
        }

        .send-button.loading svg {
            visibility: hidden;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 8px 12px;
            background-color: #f5f5f5;
            border-radius: 8px;
            width: fit-content;
            margin: 0 auto 24px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: var(--thu-purple);
            border-radius: 50%;
            animation: typingAnimation 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typingAnimation {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-4px); }
        }

        .loading {
            color: var(--thu-purple);
            font-size: 14px;
        }

        .cancel-button {
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            margin-left: 8px;
        }

        .error-message {
            color: #dc3545;
            font-size: 14px;
            margin-top: 8px;
            text-align: center;
        }

        .hierarchical-content {
            margin: 0;
        }

        .hierarchical-content h3 {
            font-size: 1.1em;
            margin-top: 16px;
            color: var(--thu-purple);
        }

        .hierarchical-content h4 {
            font-size: 1em;
            margin-top: 12px;
            color: #2c3e50;
        }

        .hierarchical-content ul {
            padding-left: 20px;
            margin: 8px 0;
        }

        .hierarchical-content li {
            margin-bottom: 4px;
        }

        .hierarchical-content p {
            margin-bottom: 8px;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .empty-state svg {
            width: 48px;
            height: 48px;
            margin-bottom: 16px;
            fill: #999;
        }

        .empty-state p {
            margin: 0;
            font-size: 14px;
        }

        .message-references {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #e6e6e6;
        }

        .reference-item {
            margin-bottom: 12px;
            padding: 12px;
            background-color: #f9f9f9;
            border-radius: 6px;
            font-size: 14px;
        }

        .reference-similarity {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
        }

        .reference-content {
            margin-top: 8px;
            color: #333;
            line-height: 1.5;
        }
    </style>
    <script>
        let currentChatId = null;
        let messageHistory = [];

        // 加载所有对话历史
        async function loadChats() {
            try {
                const response = await fetch('/api/chats');
                const chats = await response.json();
                const chatHistory = document.querySelector('.chat-history');
                chatHistory.innerHTML = '';
                
                chats.forEach(chat => {
                    const chatItem = document.createElement('div');
                    chatItem.className = 'chat-history-item';
                    if (chat.id === currentChatId) {
                        chatItem.classList.add('active');
                    }
                    chatItem.dataset.chatId = chat.id;
                    chatItem.innerHTML = `
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
                            <path d="M12 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/>
                        </svg>
                        <span class="chat-history-title">${chat.title || '新对话'}</span>
                        <button class="delete-btn" onclick="deleteChat(event, '${chat.id}')">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                                <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                            </svg>
                        </button>
                    `;
                    chatItem.onclick = () => loadChat(chat.id);
                    chatHistory.appendChild(chatItem);
                });

                // 如果没有对话历史且当前没有选中的对话，显示空状态
                if (chats.length === 0 && !currentChatId) {
                    document.querySelector('.chat-messages').innerHTML = showEmptyState();
                }
            } catch (error) {
                console.error('加载对话历史失败:', error);
            }
        }

        // 加载特定对话
        async function loadChat(chatId) {
            try {
                const response = await fetch(`/api/chats/${chatId}`);
                const chat = await response.json();
                currentChatId = chat.id;
                messageHistory = chat.messages || [];
                
                // 清空并重新显示消息
                const chatMessages = document.querySelector('.chat-messages');
                chatMessages.innerHTML = '';
                messageHistory.forEach(msg => {
                    displayMessage(msg.content, msg.role === 'assistant', msg.source, msg.references);
                });
                
                // 更新活动状态
                document.querySelectorAll('.chat-history-item').forEach(item => {
                    item.classList.remove('active');
                    if (item.dataset.chatId === chatId) {
                        item.classList.add('active');
                    }
                });
            } catch (error) {
                console.error('加载对话失败:', error);
            }
        }

        // 创建新对话
        async function createNewChat() {
            try {
                const response = await fetch('/api/chats', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        title: '新对话',
                        messages: []
                    })
                });
                const newChat = await response.json();
                currentChatId = newChat.id;
                messageHistory = [];
                document.querySelector('.chat-messages').innerHTML = '';
                await loadChats();
            } catch (error) {
                console.error('创建新对话失败:', error);
            }
        }

        // 更新对话
        async function updateChat() {
            if (!currentChatId) return;
            
            try {
                await fetch('/api/chats', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        id: currentChatId,
                        title: messageHistory[0]?.content.substring(0, 30) || '新对话',
                        messages: messageHistory
                    })
                });
            } catch (error) {
                console.error('更新对话失败:', error);
            }
        }

        // 显示消息
        function displayMessage(content, isAssistant, source = null, references = []) {
            const chatMessages = document.querySelector('.chat-messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isAssistant ? 'assistant-message' : 'user-message'}`;
            
            let messageHTML = `<div class="message-content">${content}</div>`;
            
            if (source) {
                messageHTML += `<div class="message-source">${source === 'vector_db' ? '来自知识库' : '来自AI模型'}</div>`;
            }
            
            if (isAssistant && references && references.length > 0) {
                messageHTML += `
                    <div class="message-references">
                        <h4>参考来源：</h4>
                        ${references.map(ref => `
                            <div class="reference-item">
                                <div class="reference-similarity">相关度：${(ref.similarity * 100).toFixed(1)}%</div>
                                <div class="reference-content">${ref.content}</div>
                            </div>
                        `).join('')}
                    </div>
                `;
            }
            
            messageHTML += `
                <div class="message-time">
                    ${new Date().toLocaleTimeString()}
                </div>
            `;
            
            messageDiv.innerHTML = messageHTML;
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 显示加载中状态
        function showTypingIndicator() {
            const chatMessages = document.querySelector('.chat-messages');
            const typingDiv = document.createElement('div');
            typingDiv.className = 'message assistant-message typing';
            typingDiv.innerHTML = `
                <div class="message-content">
                    正在思考
                    <div class="typing-indicator">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
            `;
            chatMessages.appendChild(typingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            return typingDiv;
        }

        // 移除加载中状态
        function removeTypingIndicator() {
            const typingIndicator = document.querySelector('.message.typing');
            if (typingIndicator) {
                typingIndicator.remove();
            }
        }

        // 调整输入框高度
        function adjustTextareaHeight() {
            const textarea = document.getElementById('message-input');
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
        }

        // 修改发送消息的函数
        async function sendMessage() {
            const input = document.getElementById('message-input');
            const message = input.value.trim();
            if (!message) return;

            // 如果没有当前对话，创建新对话
            if (!currentChatId) {
                await createNewChat();
            }

            displayMessage(message, false);
            input.value = '';
            adjustTextareaHeight();

            const typingIndicator = showTypingIndicator();

            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        history: messageHistory,
                        chatId: currentChatId
                    })
                });

                const data = await response.json();
                if (data.error) {
                    throw new Error(data.error);
                }

                removeTypingIndicator();
                displayMessage(data.answer, true, data.source, data.references);
                messageHistory = data.history;
                await updateChat();
            } catch (error) {
                console.error('发送消息失败:', error);
                removeTypingIndicator();
                displayMessage('抱歉，处理您的消息时出现错误。', true);
            }
        }

        // 删除对话
        async function deleteChat(event, chatId) {
            event.stopPropagation();
            if (!confirm('确定要删除这个对话吗？')) return;
            
            try {
                await fetch(`/api/chats/${chatId}`, {
                    method: 'DELETE'
                });
                
                if (currentChatId === chatId) {
                    currentChatId = null;
                    messageHistory = [];
                    document.querySelector('.chat-messages').innerHTML = showEmptyState();
                }
                
                await loadChats();
            } catch (error) {
                console.error('删除对话失败:', error);
            }
        }

        // 显示空状态
        function showEmptyState() {
            return `
                <div class="empty-state">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                        <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
                    </svg>
                    <p>开始一个新的对话</p>
                </div>
            `;
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 显示初始空状态
            document.querySelector('.chat-messages').innerHTML = showEmptyState();
            
            // 加载对话历史
            loadChats();
            
            // 绑定新对话按钮事件
            document.querySelector('.new-chat-btn').onclick = createNewChat;
            
            // 绑定发送按钮事件
            document.querySelector('.send-button').onclick = sendMessage;
            
            // 绑定输入框回车事件
            const input = document.getElementById('message-input');
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 自动调整输入框高度
            input.addEventListener('input', adjustTextareaHeight);
        });
    </script>
</head>
<body>
    <div class="main-container">
        <div class="sidebar">
            <button class="new-chat-btn">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
                </svg>
                新对话
            </button>
            <div class="chat-history">
                <!-- 对话历史将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <div class="chat-container">
            <div class="chat-header">
                <h2>{{ title }}</h2>
            </div>
            
            <div class="chat-messages">
                <!-- 消息将在这里动态添加 -->
            </div>
            
            <div class="input-container">
                <div class="input-group">
                    <textarea id="message-input" placeholder="输入您的问题..." rows="1"></textarea>
                    <div class="send-button-container">
                        <button class="send-button" id="send-button">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>